package org.finesys.chat.core.base.embedding;

import java.util.ArrayList;
import java.util.List;

public class Embedding {

    private final double[] vector;

    public Embedding(double[] vector) {
        this.vector = vector;
        if (vector == null) {
            throw new IllegalArgumentException("Vector cannot be null");
        }
    }

    public double[] getVector() {
        return vector;
    }

    public float[] getVectorFloat() {
        float[] vectorFloat = new float[vector.length];
        for (int i = 0; i < vector.length; i++) {
            vectorFloat[i] = (float) vector[i];
        }
        return vectorFloat;
    }

    public List<Double> vectorAsList() {
        List<Double> list = new ArrayList<>(vector.length);
        for (double v : vector) {
            list.add(v);
        }
        return list;
    }

    public int dimension() {
        return vector.length;
    }

    /**
     * 对向量进行归一化处理。
     *
     * <p>将向量的长度归一化为1，即将向量中的每个元素除以向量的模长，使其满足单位长度。
     */
    public void normalize() {
        double norm = 0.0;
        for (double v : vector) {
            norm += v * v;
        }
        norm = Math.sqrt(norm);
        for (int i = 0; i < vector.length; i++) {
            vector[i] /= norm;
        }
    }

    public static Embedding from(double[] vector) {
        return new Embedding(vector);
    }

    public static Embedding from(float[] vector) {
        double[] vectorArray = new double[vector.length];
        for (int i = 0; i < vector.length; i++) {
            vectorArray[i] = vector[i];
        }
        return new Embedding(vectorArray);
    }


    public static Embedding from(List<Double> vector) {
        double[] vectorArray = new double[vector.size()];
        for (int i = 0; i < vector.size(); i++) {
            vectorArray[i] = vector.get(i);
        }
        return new Embedding(vectorArray);
    }
}
